﻿using FRMS.BUS;
using FRMS.DAL;
using FRMS.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace FRMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RequestController : ControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private JwtSettings _jwtSettings;
        IHttpContextAccessor _access;
        public RequestController(IHostingEnvironment hostingEnvironment, IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access
        )
        {
            _hostingEnvironment = hostingEnvironment;
            _jwtSettings = jwtSettingsAccesser.Value;
            _access = access;
        }

        [HttpPost]
        [Route("Request")]
        public string Request(Object obj)
        {
            RegisterMsg register = new RegisterMsg();
            RequsetBUS requsetBUS = new RequsetBUS();
            register = JsonConvert.DeserializeObject<RegisterMsg>(obj.ToString());
            if (register.Name == "registerRequest")
            {
                RegisterMsgReturn registerMsgReturn = new RegisterMsgReturn();
                RegisterMsgReturnData registerMsgReturnData = new RegisterMsgReturnData();
                string user_name = register.User;
                string user_pwd = register.Pwd;
                HomeDAL homeDAL = new HomeDAL();
                User user1 = homeDAL.CheckName(user_name);
                if (user1 != null)
                {
                    User user = homeDAL.GetUser(user_name, user_pwd);
                    if (user != null)
                    {
                        registerMsgReturn.Name = "registerResponse";
                        registerMsgReturnData.ProjectID = user.projectID;
                        registerMsgReturnData.Pwd = user.LoginPwd;
                        registerMsgReturnData.User = user.LoginName;
                        Random random = new Random();
                        int random_num = random.Next(1, 999999);
                        string session = "fx" + user.projectID.ToString().PadLeft(3, '0') + random_num.ToString().PadLeft(6, '0');
                        ProjectDAL projectDAL = new ProjectDAL();
                        bool result = projectDAL.UpdateProjectSession(session, user.projectID);
                        if (result)
                        {
                            registerMsgReturn.Code = 1;
                            registerMsgReturnData.Session = session;
                            registerMsgReturn.Message = "success";
                        }
                        else
                        {
                            registerMsgReturn.Code = -4;
                            registerMsgReturn.Message = "获取session异常";
                        }
                    }
                    else
                    {
                        registerMsgReturn.Code = -2;
                        registerMsgReturn.Message = "密码不正确";
                    }
                }
                else
                {
                    registerMsgReturn.Code = -1;
                    registerMsgReturn.Message = "账户不存在";
                }

                registerMsgReturn.Data = registerMsgReturnData;
                string message = JsonConvert.SerializeObject(registerMsgReturn);
                return message;
            }
            else if (register.Name == "refreshRequest")
            {
                RefreshSessionMsgReturn refreshSessionMsgReturn = new RefreshSessionMsgReturn();
                RefreshSessionMsg refreshSessionMsg = JsonConvert.DeserializeObject<RefreshSessionMsg>(obj.ToString());
                string user_name = refreshSessionMsg.User;
                string user_pwd = refreshSessionMsg.Pwd;
                HomeDAL homeDAL = new HomeDAL();
                User user1 = homeDAL.CheckName(user_name);
                if (user1 != null)
                {
                    User user = homeDAL.GetUser(user_name, user_pwd);
                    if (user != null)
                    {
                        refreshSessionMsgReturn.Name = "refreshResponse";
                        Random random = new Random();
                        int random_num = random.Next(1, 999999);
                        string session = "fx" + user.projectID.ToString().PadLeft(3, '0') + random_num.ToString().PadLeft(6, '0');
                        ProjectDAL projectDAL = new ProjectDAL();
                        bool result = projectDAL.UpdateProjectSession(session, user.projectID);
                        if (result)
                        {
                            refreshSessionMsgReturn.Message = "success";
                            refreshSessionMsgReturn.Code = 1;
                            refreshSessionMsgReturn.Session = session;
                        }
                        else
                        {
                            refreshSessionMsgReturn.Code = -4;
                            refreshSessionMsgReturn.Message = "获取session异常";
                        }
                    }
                    else
                    {
                        refreshSessionMsgReturn.Code = -2;
                        refreshSessionMsgReturn.Message = "密码不正确";
                    }
                }
                else
                {
                    refreshSessionMsgReturn.Code = -1;
                    refreshSessionMsgReturn.Message = "账户不存在";
                }
                string message = JsonConvert.SerializeObject(refreshSessionMsgReturn);
                return message;
            }
            else if (register.Name == "addPersonRequest")
            {
                AddPersonMsgReturn addPersonMsgReturn = new AddPersonMsgReturn();
                addPersonMsgReturn.Name = "addPersonResponse";
                AddPersonMsg addPersonMsg = JsonConvert.DeserializeObject<AddPersonMsg>(obj.ToString());
                HomeDAL homeDAL = new HomeDAL();
                ProjectInfo projectInfo = homeDAL.CheckSession(addPersonMsg.Session);
                if (projectInfo != null)
                {
                    if (projectInfo.ID != addPersonMsg.Data.ProjectID)
                    {
                        addPersonMsgReturn.Code = -12;
                        addPersonMsgReturn.Message = "项目ID不正确";
                    }
                    else
                    {
                        try
                        {
                            OwnerInfo ownerInfo = new OwnerInfo();
                            ownerInfo.UUID = GetUUID(addPersonMsg.Data.ProjectID);
                            ownerInfo.OwnerType = GetOwnerType(addPersonMsg.Data.PersonType);
                            if (!string.IsNullOrEmpty(addPersonMsg.Data.FacePicture))
                            {
                                string webRootPath = _hostingEnvironment.ContentRootPath;
                                ownerInfo.PicturePath = requsetBUS.Base64ToImage(addPersonMsg.Data.FacePicture, webRootPath);
                            }
                            if (!string.IsNullOrEmpty(addPersonMsg.Data.CardNO))
                            {
                                ownerInfo.VirtualCard = 0;
                            }
                            else
                            {
                                ownerInfo.VirtualCard = 1;
                            }

                            List<AddPersonMsgAuthData> list = addPersonMsg.Data.AuthData;
                            foreach (var item in list)
                            {
                                BuildInfo buildInfo = new BuildInfo();
                                buildInfo.projectID = projectInfo.ID;
                                buildInfo.BuildingName = item.UnitName;
                                BuildDAL buildDAL = new BuildDAL();
                                int buildid = buildDAL.QueryBuildID(item.UnitName, projectInfo.ID);
                                if (buildid <= 0)
                                {
                                    buildid = buildDAL.AddBuild_1(buildInfo);
                                }
                                RoomDAL roomDAL = new RoomDAL();
                                int roomid = roomDAL.CheckRoomID(buildid, item.RoomName, 0);
                                if (roomid <= 0)
                                {
                                    RoomInfo roomInfo = new RoomInfo();
                                    roomInfo.projectID = projectInfo.ID;
                                    roomInfo.BuildID = buildid;
                                    roomInfo.RoomName = item.RoomName;
                                    roomid = roomDAL.AddRoom_1(roomInfo);
                                }
                                ownerInfo.RoomID = roomid;

                                DeviceDAL deviceDAL = new DeviceDAL();
                                int dev_id = deviceDAL.CheckDeviceByIp(item.DeviceIP, projectInfo.ID);
                                if (dev_id <= 0)
                                {
                                    DeviceInfo deviceInfo = new DeviceInfo();
                                    deviceInfo.DeviceIP = item.DeviceIP;
                                    deviceInfo.projectID = projectInfo.ID;
                                    dev_id = deviceDAL.AddDevice_1(deviceInfo);
                                }
                                OwnerDAL ownerDAL = new OwnerDAL();
                                int ownerid = ownerDAL.AddOwner_1(ownerInfo);
                                VoucherInfo voucherInfo = new VoucherInfo();
                                voucherInfo.DeviceID = dev_id;
                                voucherInfo.OwnerID = ownerid;
                                voucherInfo.AuthorizedFloor = item.AuthFloor;
                                voucherInfo.EffectiveStarttime = item.StartTime;
                                voucherInfo.EffectiveEndtime = item.EndTime;
                                VoucherDAL voucherDAL = new VoucherDAL();
                                voucherDAL.AddVoucher(voucherInfo);
                            }
                            addPersonMsgReturn.Code = 0;
                            addPersonMsgReturn.Session = projectInfo.Session;
                        }
                        catch
                        {
                            addPersonMsgReturn.Code = -3;
                            addPersonMsgReturn.Message = "新增异常";
                        }
                    }
                }
                else
                {
                    addPersonMsgReturn.Code = -3;
                    addPersonMsgReturn.Message = "session不匹配";
                }
                string message = JsonConvert.SerializeObject(addPersonMsgReturn);
                return message;
            }
            else if (register.Name == "updatePersonRequest")
            {
                UpdatePersonMsgReturn updatePersonMsgReturn = new UpdatePersonMsgReturn();
                updatePersonMsgReturn.Name = "updatePersonResponse";
                UpdatePersonMsg updatePersonMsg = JsonConvert.DeserializeObject<UpdatePersonMsg>(obj.ToString());
                HomeDAL homeDAL = new HomeDAL();
                ProjectInfo projectInfo = homeDAL.CheckSession(updatePersonMsg.Session);
                if (projectInfo != null)
                {
                    if (projectInfo.ID != updatePersonMsg.Data.ProjectID)
                    {
                        updatePersonMsgReturn.Code = -12;
                        updatePersonMsgReturn.Message = "项目ID不正确";
                    }
                    else
                    {
                        OwnerInfo ownerInfo = new OwnerInfo();
                        ownerInfo.OwnerType = GetOwnerType(updatePersonMsg.Data.PersonType);
                        if (!string.IsNullOrEmpty(updatePersonMsg.Data.FacePicture))
                        {
                            string webRootPath = _hostingEnvironment.ContentRootPath;
                            ownerInfo.PicturePath = requsetBUS.Base64ToImage(updatePersonMsg.Data.FacePicture, webRootPath);
                        }
                        else
                        {
                            ownerInfo.PicturePath = "";
                        }
                        if (!string.IsNullOrEmpty(updatePersonMsg.Data.CardNO))
                        {
                            ownerInfo.VirtualCard = 0;
                        }
                        else
                        {
                            ownerInfo.VirtualCard = 1;
                        }
                        ownerInfo.Phone = updatePersonMsg.Data.Phone;
                        ownerInfo.CertificateNO = updatePersonMsg.Data.CertificateNO;
                        OwnerDAL ownerDAL = new OwnerDAL();
                        bool result = ownerDAL.UpdateOwner_1(ownerInfo);
                        if (result)
                        {
                            VoucherDAL voucherDAL = new VoucherDAL();
                            foreach (var item in updatePersonMsg.Data.AuthData)
                            {
                                VoucherInfo voucherInfo = new VoucherInfo();
                                voucherInfo.DeviceIP = item.DeviceIP;
                                voucherInfo.AuthorizedFloor = item.AuthFloor;
                                voucherInfo.EffectiveEndtime = item.EndTime;
                                voucherInfo.EffectiveStarttime = item.StartTime;
                                voucherDAL.UpdateVoucher_1(voucherInfo);
                            }
                            updatePersonMsgReturn.Code = 1;
                            updatePersonMsgReturn.Message = "success";
                            updatePersonMsgReturn.Session = projectInfo.Session;
                        }
                        else
                        {
                            updatePersonMsgReturn.Code = -13;
                            updatePersonMsgReturn.Message = "更新业主信息失败";
                        }
                    }
                }
            }
            else if (register.Name == "deletePersonRequest")
            {
                DeletePersonMsgReturn deletePersonMsgReturn = new DeletePersonMsgReturn();
                deletePersonMsgReturn.Name = "deletePersonResponse";
                DeletePersonMsg deletePersonMsg = JsonConvert.DeserializeObject<DeletePersonMsg>(obj.ToString());
                HomeDAL homeDAL = new HomeDAL();
                ProjectInfo projectInfo = homeDAL.CheckSession(deletePersonMsg.Session);
                if (projectInfo != null)
                {
                    if (projectInfo.ID != deletePersonMsg.Data.ProjectID)
                    {
                        deletePersonMsgReturn.Code = -12;
                        deletePersonMsgReturn.Message = "项目ID不正确";
                        deletePersonMsgReturn.Session = projectInfo.Session;
                    }
                    else
                    {
                        List<DeletePersonMsgAuthData> list = deletePersonMsg.Data.AuthData;
                        VoucherDAL voucherDAL = new VoucherDAL();
                        foreach (var item in list)
                        {
                            voucherDAL.DeleteVoucherByOwner(item.DeviceIP, deletePersonMsg.Data.PersonUuid);
                        }
                        deletePersonMsgReturn.Code = 0;
                        deletePersonMsgReturn.Message = "success";
                        deletePersonMsgReturn.Session = projectInfo.Session;
                    }
                }
                else
                {
                    deletePersonMsgReturn.Code = -3;
                    deletePersonMsgReturn.Message = "session不匹配";
                }
                string message = JsonConvert.SerializeObject(deletePersonMsgReturn);
                return message;
            }
            else if (register.Name == "liftModeRequest")
            {
                LiftModeMsgReturn liftModeMsgReturn = new LiftModeMsgReturn();
                liftModeMsgReturn.Name = "liftModeResponse";
                LiftModeMsg liftModeMsg = JsonConvert.DeserializeObject<LiftModeMsg>(obj.ToString());
                HomeDAL homeDAL = new HomeDAL();
                ProjectInfo projectInfo = homeDAL.CheckSession(liftModeMsg.Session);
                if (projectInfo != null)
                {
                    if (projectInfo.ID != liftModeMsg.Data.ProjectID)
                    {
                        liftModeMsgReturn.Code = -12;
                        liftModeMsgReturn.Message = "项目ID不正确";
                        liftModeMsgReturn.Session = projectInfo.Session;
                    }
                    else
                    {
                        ElevatorDAL elevatorDAL = new ElevatorDAL();
                        bool result = elevatorDAL.UpdateMode(liftModeMsg.Data.LiftName, liftModeMsg.Data.UnitName, liftModeMsg.Data.LiftMode);
                        if (result)
                        {
                            liftModeMsgReturn.Code = 1;
                            liftModeMsgReturn.Session = projectInfo.Session;
                        }
                        else
                        {
                            liftModeMsgReturn.Code = 0;
                            liftModeMsgReturn.Session = projectInfo.Session;
                            liftModeMsgReturn.Message = "更新失败";
                        }
                    }
                }
                else
                {
                    liftModeMsgReturn.Code = -3;
                    liftModeMsgReturn.Message = "session不匹配";
                }

            }
            return "";
        }

        public int GetOwnerType(string typename)
        {
            int type = -1;
            switch (typename)
            {
                case "业主": type = 1; break;
                case "物业": type = 2; break;
                case "租客": type = 4; break;
                case "访客": type = 5; break;
                case "其他": type = 6; break;
            }
            return type;
        }

        public string GetUUID(int projectid)
        {
            string uuid = string.Empty;
            bool result = true;
            OwnerDAL da = new OwnerDAL();
            ProjectDAL projectDAL = new ProjectDAL();
            ProjectInfo projectInfo = projectDAL.LoadProject(projectid);
            while (result)
            {
                Random random = new Random();
                int randomid = random.Next(1, 999999);
                uuid = Convert.ToInt32(projectInfo.project_code).ToString("X").PadLeft(2, '0') + randomid.ToString().PadLeft(6, '0');
                result = da.CheckUUID(uuid);
            }
            return uuid;
        }

        //[HttpPost]
        //[Route("AddAudit")]

        //public AddAuditInfoReturn AddAudit(AddAuditInfo addAuditInfo)
        //{
        //    AddAuditInfoReturn addAuditInfoReturn = new AddAuditInfoReturn();
        //    addAuditInfoReturn.method = "addaudit";
        //    try
        //    {
        //        if (addAuditInfo.method == "addaudit")
        //        {
        //            RequsetBUS requsetBUS = new RequsetBUS();
        //            addAuditInfoReturn = requsetBUS.addAuditInfo(addAuditInfo);

        //        }else
        //        {
        //            addAuditInfoReturn.code = 1;
        //            addAuditInfoReturn.msg = "同步申请记录method参数错误";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        addAuditInfoReturn.code = 1;
        //        addAuditInfoReturn.msg = "同步申请记录异常";
        //    }
        //    return addAuditInfoReturn;
        //}

    }
}
